package com.richapp.launcher.utils;

import java.util.Stack;

import android.app.Activity;
import android.util.Log;

/**
 * Activity栈管理
 * @author penglin
 * @version TVLAUNCHER001, 2013-12-6
 */
public class MyActivityManager {

    private static final String TAG = "MyActivityManager";

    private static Stack<Activity> activityStack;

    private static MyActivityManager instance;

    private MyActivityManager() {
        Log.v("info"," ***** create MyActivityManager ******");
    }

    public static MyActivityManager getInstance() {
        if (instance == null) {
            instance = new MyActivityManager();
            if (activityStack == null) {
                activityStack = new Stack<Activity>();
            }
        }
        return instance;
    }

    /**
     * @return
     */
    public int getActivitySize() {
        return activityStack.size();
    }

    /**
     * 栈当前acitvity
     * @return
     */
    public Activity currentActivity() {
        Activity activity = null;
        try {
            activity = activityStack.lastElement();
        } catch (Exception e) {
            //            Logger.getLogger().e("Has come to the end ");
        }
        return activity;
    }

    /**
     * 入栈
     * @param activity
     */
    public void pushActivity(Activity activity) {
        Log.v("info" ,activity+"");
        activityStack.add(activity);
        //        Logger.getLogger().d("push stack item " + activity.getClass());
    }

    /**
     * 出栈
     */
    public void popActivityFinish() {
        popActivityFinish(currentActivity());
    }

    /**
     * 移出栈某一个activity
     * @param activity
     */
    public void popActivityFinish(Activity activity) {
        if (activity != null) {
            activity.finish();
            activityStack.remove(activity);
            activity = null;
        }
    }

    /**
     * 出栈但不finish Activity
     * @param activity
     */
    public void popActivityNotFinish(Activity activity) {
       Log.v("info" ,activity+"");
        if (activity != null) {
            activityStack.remove(activity);
            activity = null;
        }
    }

    public void popAllActivityExceptOne(Class cls) {
       Log.v("info" ,cls+"");
        while (true) {
            Activity activity = currentActivity();
            if (activity == null || activity == activityStack.firstElement()) {
                break;
            }
            if (activity.getClass().equals(cls)) {
                continue;
            } else {
                popActivityFinish(activity);
            }
        }
    }

    public void popAllActivity() {
        while (true) {
            Activity activity = currentActivity();
            if (activity == null) {
                break;
            }
            popActivityFinish(activity);
        }
    }

}
